package cn.kgc.controller;

import cn.kgc.common.ResultEntity;
import cn.kgc.pojo.Menu;
import cn.kgc.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-02-28 9:03
 */
@Controller
public class MenuController {


    @Resource
    MenuService menuService;

    @ResponseBody
    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree() {
        //查询所有树形节点用于组装  所有数据存储到menuList中
        List<Menu> menuList = menuService.getAll();
        //将menuList转换成 map集合形式
        Map<Integer, Menu> menuMap = new HashMap<>();

        for (Menu menu : menuList) {
            menuMap.put(menu.getId(), menu);
        }
        //申明存储更节点对象
        Menu root = null;

        for (Menu menu : menuList) {
            //如果父节点为null  把父节点存储root 中  继续运行  跳出
            if (menu.getPid() == null) {
                root = menu;
                continue;
            }
            //是子节点从menuMap找到父节点,添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);
        }
        return ResultEntity.successWithoutData(root);
    }


    //增加
    @ResponseBody
    @RequestMapping("/menu/save")
    public ResultEntity<String> menusave(Menu menu) {
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    //修改前的查询
    @ResponseBody
    @RequestMapping("/menu/get/{menuId}")
    public ResultEntity<Menu> menugetid(@PathVariable Integer menuId) {
        Menu menuById = menuService.getMenuById(menuId);
        return ResultEntity.successWithoutData(menuById);
    }

    //修改
    @RequestMapping("/menu/update")
    @ResponseBody
    public ResultEntity<String> menuupdate(Menu menu) {
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    //删除
    @ResponseBody
    @RequestMapping("/menu/delete/{menuId}")
    public ResultEntity<String> menudelete(@PathVariable("menuId") Integer menuId) {
        menuService.batchRemove(menuId);
        return ResultEntity.successWithoutData();
    }
}
